# coding=utf-8

from redis_helper import RedisHelper
from mysql import Mysql
import hashlib

def main():
    name = input('请输入用户名:')
    pwd = input('请输入密码:')

    # 密码加密
    shash = hashlib.sha1()
    shash.update(pwd.encode('utf-8'))
    npwd = shash.hexdigest()

    # 查询redis中是否有记录
    rds = RedisHelper('localhost', 6379)
    msql = Mysql('localhost', 'lyh', '123', 'python')

    # 如果redis中没有此用户的数据，则会去mysql数据库进行查询，
    # 并且将用户信息放在redis中，在下次请求中可直接在redis中使用
    if None == rds.get(name):
        sql = 'select passwd from users where uname=%s'
        result = msql.all(sql, [name])
        if 0 == len(result):
            print('没有此用户!')
        elif npwd == result[0][0]:
            rds.set(name, npwd)
            print('登陆成功!')
        else:
            print('密码错误!')

    else:
        if npwd == rds.get(name).decode('utf-8'):
            print('登陆成功!')
        else:
            print('登陆失败!')

if __name__ == '__main__':
    main()
